//
//  ImageDownloader.m
//  NewsReader
//
//  Created by blacksun on 10-11-23.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ImageDownloader.h"
#import "NewsReaderAppDelegate.h"


@implementation ImageDownloader
@synthesize identifier,delegate,activeDownload,imageConnection,imageUrl;



-(void)dealloc{
	[self.identifier release];
	[self.activeDownload release];
	[self.imageConnection release];
	[self.imageUrl release];
	[super dealloc];
}

- (void)startDownload
{
	if (![HttpUtil isNetworkUseable]) {
		[HttpUtil showUsageAlertDialog];
		return;
	}
	/*srand([[NSDate date] timeIntervalSince1970]); 
	int rand = (int)random()%5+1;
	
	if (applicationDelegate.isGFW) {
		NSString *imageServler = [[NSString alloc] initWithFormat:@"http://image%d.ipointstyle.com/",rand];
		NSString *temp = [[NSString alloc] initWithFormat:@"%@",[imageUrl stringByReplacingOccurrencesOfString:@"http://ipoint-imgserver.appspot.com/" withString:imageServler]];
		self.imageUrl = temp;
		[temp release];
		[imageServler release];
	}else {
		NSString *imageServler = [[NSString alloc] initWithFormat:@"http://image%d.ipoint.mobi/",rand];
		NSString *temp = [[NSString alloc] initWithFormat:@"%@",[imageUrl stringByReplacingOccurrencesOfString:@"http://ipoint-imgserver.appspot.com/" withString:imageServler]];
		self.imageUrl = temp;
		[temp release];
		[imageServler release];
	}*/
	NSString *url = [[NSString alloc] initWithFormat:@"%@%@",[URLAddress getUrl],imageUrl];
    //NSLog(@"%@",url);
	self.imageUrl = url;
	[url release];
	NSMutableData *data = [[NSMutableData alloc] init];
    self.activeDownload = data;
	[data release];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
                             [NSURLRequest requestWithURL:
                              [NSURL URLWithString:imageUrl]] delegate:self];
	[NSTimer scheduledTimerWithTimeInterval:kRequestTimeOut target:self selector:@selector(connectionTimeOut) userInfo:nil repeats:NO];
    self.imageConnection = conn;
	isConnectioning = YES;
    [conn release];
}
-(void)connectionTimeOut{
	if (!isConnectioning) return;
	[self cancelDownload];
	
}


- (void)cancelDownload
{
	isConnectioning = NO;
	[self.imageConnection cancel];
    self.imageConnection = nil;
    self.activeDownload = nil;
}


#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
	NSInteger statusCode = [httpResponse statusCode];
	if (statusCode == 503 && retryCount < kMaxRetryCount) {
		[self cancelDownload];
		[self performSelectorOnMainThread:@selector(startDownload) withObject:nil waitUntilDone:YES];
		retryCount ++;
	}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.activeDownload = nil;
    self.imageConnection = nil;
	isConnectioning = NO;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    // Set appIcon and clear temporary data/image
    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
	[delegate imageLoaded:image forIdentify:identifier ];
    [image release];
    self.activeDownload = nil;
	self.imageConnection = nil;
	isConnectioning = NO;
}

@end
